//
//  CategoryCellView.m
//  JiaoX
//
//  Created by 尹桥印 on 14/11/18.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//  分类cell的view

#import "CategoryCellView.h"
#import "CategoryCellChildView.h"
#import "SubCategory.h"

@interface CategoryCellView()<CategoryCellChildViewDelegate>
{
    NSMutableArray *useViews;//正在使用的view的
    NSMutableArray *cacheViews;//没有使用的，缓存池中的view
}

@end


@implementation CategoryCellView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self!=nil){
        useViews = [NSMutableArray array];
        cacheViews = [NSMutableArray array];
    }
    return self;
}


+(instancetype)initWithSubcategoryList:(NSArray *)array{
    return [[self alloc]init];
}

-(void)setSubcategoryList:(NSArray *)subcategoryList{
    //在这个地方添加imageView。根据集合的大小添加
    // 将正在使用的view添加进cacheview；
    [cacheViews addObjectsFromArray:useViews];
    for (CategoryCellChildView *view in useViews) {
        view.itemClickDelegate = nil;
        [view removeFromSuperview];
    }
    [useViews removeAllObjects];
    int viewHeight = 0;
    for (int i=0; i<subcategoryList.count; i++) {
        SubCategory *subCategory = subcategoryList[i];
        
        CategoryCellChildView *childView = [self getChildViewWithSubCategory:subCategory];
        //        [childView removeFromSuperview];
        childView.itemClickDelegate = self;
        //计算出位置
        // 第几行
        int row = i / SUBCATEGORY_COL;
        // 第几列
        int col = i % SUBCATEGORY_COL;
        
        CGFloat viewX = (col+1)*JXPublicInset + (col*childView.width);
        CGFloat viewY = row * childView.height+(row+1)*15;
        
        childView.x = viewX;
        childView.y = viewY;
        
        viewHeight = viewY+childView.height+15;
        [self addSubview:childView];
    }
    self.width = JXScreenW;
    self.height = viewHeight;
}

//去缓存池里面取view
-(CategoryCellChildView *)getChildViewWithSubCategory:(SubCategory *)sub{
    CategoryCellChildView *view = [cacheViews firstObject];
    if(view){
        //如果view有值
        [view setSub:sub];
        [cacheViews removeObject:view];
        [useViews addObject:view];
        
    }else{
        //没有值，则init一个，返回
        view = [CategoryCellChildView initWithIconSubCategory:sub];
        [useViews addObject:view];
    }
    return view;
}

- (void)subItemClickDelegate:(SubCategory *)sub{
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(subItemClickDelegate:)]) {
        [self.delegate subItemClickDelegate:sub];
    }
}

@end
